package com.cqc.recyclerviewdemo02;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by ${cqc} on 2016/12/2.
 */

public class StaggeredGridActivity extends AppCompatActivity {


    private RecyclerView recyclerView;
    private List<String> list = new ArrayList<>();
    private List<Integer> heights = new ArrayList<>();
    private RecyclerStaggeredAdapter adapter;
    private Toast toast;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toast = Toast.makeText(StaggeredGridActivity.this, "", Toast.LENGTH_SHORT);
        initData();

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));//GridLayoutManager(MainActivity.this, 3)
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerGridItemDecoration(StaggeredGridActivity.this));
        adapter = new RecyclerStaggeredAdapter(list,heights);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new RecyclerStaggeredAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                toast.setText(list.get(position));
                toast.show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add:
                list.add(1, "add");
                heights.add(1,new Random().nextInt(100)+100);
                adapter.notifyItemInserted(1);//list中的position需要与notifyItemInserted(1)中的i一致。
                break;
            case R.id.delete:
                list.remove(3);
                heights.remove(3);
                adapter.notifyItemRemoved(3);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initData() {
        list.clear();
        heights.clear();
        Random random = new Random();
        for (int i = 'A'; i < 'Z'; i++) {
            list.add("" + (char) i);
            heights.add(random.nextInt(100) + 100);
        }
    }
}
